package cn.shanke.torrentmanagerserver.controller;

import cn.shanke.torrentmanagerserver.controller.common.ResponseModel;
import cn.shanke.torrentmanagerserver.model.User;
import cn.shanke.torrentmanagerserver.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping
    public ResponseModel listModels(
            @RequestParam(required = false)String name
    ) {
        QueryWrapper<User> query = new QueryWrapper<>();
        if (name!=null && name.length()>0) {
            query.lambda().like(User::getName, name);
        }
        return ResponseModel.success().data(userService.list(query));
    }

    @GetMapping(value = "/{id}")
    public ResponseModel getModelById(@PathVariable("id")Long id) {
        return ResponseModel.success().data(userService.getById(id));
    }

    @PostMapping
    public ResponseModel addModel() {
        User user = new User();
        user.setName("shanke");
        user.setAge(30);
        user.setEmail("1@a.com");
        userService.save(user);
        return ResponseModel.success().data(user.getId());
    }

    @PutMapping
    public ResponseModel updateModel(@RequestBody User user) {
        userService.updateById(user);
        return ResponseModel.success();
    }

    @DeleteMapping("/{id}")
    public ResponseModel deleteModel(@PathVariable("id")Long id) {
        userService.removeById(id);
        return ResponseModel.success();
    }
}
